package com.example.repository.impl;

import com.example.entity.Student;
import com.example.repository.StudentRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;


@Repository
@Transactional
public class StudentRepositoryImpl implements StudentRepository {

    // 使用了@PersistenceUnit注解，因此Spring会将EntityManagerFactory注入进来
    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;

    @Override
    public void add(Student student) {
        entityManagerFactory.createEntityManager().persist(student);
    }

    @Override
    public Student getById(Integer id) {
        return entityManagerFactory.createEntityManager().find(Student.class, id);
    }

    @Override
    public void save(Student student) {
        entityManagerFactory.createEntityManager().merge(student);
    }
}
